package cn.kogee.user.service.impl;

import cn.kogee.basic.constants.VerifyCodeConstants;
import cn.kogee.basic.exception.BusinessException;
import cn.kogee.basic.service.impl.BaseServiceImpl;
import cn.kogee.basic.util.Md5Utils;
import cn.kogee.basic.util.StrUtils;
import cn.kogee.user.domain.Logininfo;
import cn.kogee.user.domain.User;
import cn.kogee.user.dto.EmailDto;
import cn.kogee.user.dto.UserDto;
import cn.kogee.user.mapper.LogininfoMapper;
import cn.kogee.user.mapper.UserMapper;
import cn.kogee.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
     * 手机号注册
     * @param dto
     */
    @Override
    public void regist(UserDto dto) {

        //1.校验
        //1.1传入数据校验
        String code = dto.getCode();
        String password = dto.getPassword();
        String phone = dto.getPhone();
        String passwordRepeat = dto.getPasswordRepeat();
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(phone)
                ||StringUtils.isEmpty(phone)||
                StringUtils.isEmpty(phone)){
            throw new BusinessException("注册信息不能为空");
        }
        //1.2校验用户验证码是否过期
        String key= VerifyCodeConstants.REGISTER_CODE_PREFIX +phone;
        Object Obj = redisTemplate.opsForValue().get(key);
        if(Obj==null){
            throw new BusinessException("验证码已经过期，请重新申请");
        }
        if(!Obj.toString().split(":")[0].equals(code)){
            throw new BusinessException("验证码错误，请重新核对");
        }
        //1.3校验密码
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次输入密码不一致");
        }
        //2保存入库
        User user=User2UserDto(dto);
        Logininfo logininfo=Loginingo2User(user);
        //新增logininfo
        logininfoMapper.save(logininfo);
        //给user设置logininfoid
        user.setLogininfoId(logininfo.getId());
        //保存user
        userMapper.save(user);
    }

    /**
     * 邮箱注册
     * @param dto
     */
    @Override
    public void registemail(EmailDto dto) {
        //用户输入的邮箱
        String email = dto.getEmail();
        //密码
        String password = dto.getPassword();
        //二次输入密码
        String passwordRepeat = dto.getPasswordRepeat();
        //输入的图形验证码
        String imageCode = dto.getImageCode();
        //前端传递的图形验证码key
        String imageCodeKey = dto.getImageCodeKey();
        //1.空值校验
        if(StringUtils.isEmpty(email)||StringUtils.isEmpty(password)||
                StringUtils.isEmpty(passwordRepeat)||StringUtils.isEmpty(imageCode)){
            throw new BusinessException("注册信息不能为空");
        }
        //2.图形验证码校验是否过期
        Object imageTmp = redisTemplate.opsForValue().get(imageCodeKey);
        if(imageTmp==null){
            throw new BusinessException("验证码已经过期，请重新获取");
        }
        //3.图形验证码是否正确
        if(!imageTmp.toString().equalsIgnoreCase(imageCode)){
            throw new BusinessException("验证码错误");
        }
        //4.密码是否正确
        if(!password.equals(passwordRepeat)){

            throw new BusinessException("二次输入密码不正确");
        }
        //5.保存落库
        User user=UserTwodto(dto);
        Logininfo logininfo = Loginingo2User(user);
        logininfoMapper.save(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    private User UserTwodto(EmailDto dto) {
        User user = new User();
        user.setUsername(dto.getEmail());
        user.setEmail(dto.getEmail());
        user.setPhone(null);
        //生成盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //加盐加密
        String md5Pwd = Md5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    private User User2UserDto(UserDto dto) {
        User user = new User();
        user.setUsername(dto.getPhone());
        user.setPhone(dto.getPhone());
        //生成盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //加盐加密
        String md5Pwd = Md5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }
    private Logininfo Loginingo2User(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void del(Long id) {
        //查询出Employee表整体信息
        User user = userMapper.loadById(id);
        //根据Logininfo_id删除相关信息
        logininfoMapper.remove(user.getLogininfoId());
        super.del(id);
    }

    /**
     * 新增
     * @param user
     */
    @Override
    public void add(User user) {
        //设置盐值加密
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setPassword(md5Pwd);
        Logininfo logininfo = new Logininfo();
        //设置为管理员
        logininfo.setType(0);
        //设置管理员状态
        logininfo.setDisable(true);
        //拷贝管理员信息
        BeanUtils.copyProperties(user,logininfo);
        logininfoMapper.save(logininfo);//保存落库
        user.setLogininfoId(logininfo.getId());//给管理员设置logininfoId
        super.add(user);
    }

    /**
     * 修改
     * @param user
     */
    @Override
    public void update(User user) {
        //设置盐值加密
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setPassword(md5Pwd);
        super.update(user);
        //根据之前的id查询出之前的管理员信息
        User oldeuser = userMapper.loadById(user.getId());
        //在根据之前管理员信息的ID查询出logininfo信息
        Logininfo logininfo = logininfoMapper.loadById(oldeuser.getLogininfoId());
        //拷贝现在employee表信息
        BeanUtils.copyProperties(userMapper,logininfo);
        logininfoMapper.update(logininfo);
    }
}
